﻿using ClosedXML.Excel;
using Org.BouncyCastle.Asn1.Cmp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using xiaoxiong.KYJDAL.Models;
using xiaoxiong.KYJDAL.Services;
using xiaoxiong.ScadaProModbusRtu.Common;

namespace xiaoxiong.ScadaProModbusRtu
{
    public partial class FrmHistoryLog : Form
    {

        SysLogService SysLogService = new SysLogService();
        // 分页参数（建议改为实例成员）
        private int pageSize = 15;
        private int recordCount = 0;
        private int pageCount = 0;
        private int currentPage = 1; // 当前页码从1开始

        // 新增成员变量存储当前查询条件
        private DateTime? currentStartTime;
        private DateTime? currentEndTime;
        private string currentLogType = "";
        private bool isConditionSearch = false; // 标记是否条件查询

        //没有条件的
        List<SysLog> noTypeLogs = new List<SysLog>();
        //有条件的
        List<SysLog> typeLogs = new List<SysLog>();

        public FrmHistoryLog()
        {
            InitializeComponent();

            this.Load += FrmHistoryLog_Load ;
        }

        private async void FrmHistoryLog_Load(object sender, EventArgs e)
        {
            CbxInit();
            this.dgv_HistoryLog.AutoGenerateColumns = false;
            await LoadAllNoConditionData();
            await InitializePagination();
            await LoadPageData();
        }

        private void CbxInit()
        {
            // 初始化下拉框
            cbx_LogType.Items.Clear();

            // 获取枚举的所有值
            var logTypes = Enum.GetValues(typeof(CommonEnum));
            // 遍历枚举值并添加到下拉框
            foreach (var logType in logTypes)
            {
                cbx_LogType.Items.Add(logType);
            }
        }


        private async Task LoadPageData()
        {
            try
            {
                // 边界检查
                currentPage = Math.Max(1, Math.Min(currentPage, pageCount));

                List<SysLog> pagedData;

                if (isConditionSearch)
                {
                    // 条件分页查询
                    var result = await SysLogService.GetSysLogTimePaged(
                        currentStartTime.Value,
                        currentEndTime.Value,
                        currentLogType,
                        currentPage,
                        pageSize
                    );

                    pagedData = result.Data;
                    recordCount = result.TotalCount;  // 更新总记录数
                    pageCount = (int)Math.Ceiling(recordCount / (double)pageSize);
                }
                else
                {
                    // 普通分页查询
                    int skip = (currentPage - 1) * pageSize;
                    pagedData = await SysLogService.GetSysLogList(skip, pageSize);
                }

                dgv_HistoryLog.DataSource = null;
                dgv_HistoryLog.DataSource = pagedData;


                UpdatePaginationControls();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载失败：{ex.Message}");
            }
        }

        // 新增方法：加载无条件的全部数据
        private async Task LoadAllNoConditionData()
        {
            try
            {
                var list = await SysLogService.GetSysLogList();
                noTypeLogs = list; // 存储到成员变量
                                   // 按时间升序排序（初始化时预排序）
                noTypeLogs = list
                    .OrderBy(log => log.InsertTime)
                    .ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化数据失败：{ex.Message}");
            }
        }

        private async Task InitializePagination()
        {
            if (isConditionSearch)
            {
                // 条件查询的总数
                var countResult = await SysLogService.GetSysLogTimeCount(
                    currentStartTime.Value,
                    currentEndTime.Value,
                    currentLogType
                );
                recordCount = countResult.Count;
            }
            else
            {
                // 普通查询的总数
                var listcount = await SysLogService.GetSysLogList();
                recordCount = listcount.Count;
            }

            lbl_LogCount.Text = recordCount.ToString();
            pageCount = (int)Math.Ceiling(recordCount / (double)pageSize);
            lbl_CountPage.Text = pageCount.ToString();

            UpdatePaginationControls();
        }
        private void UpdatePaginationControls()
        {
            // 更新页码显示
            this.txt_Page.Text = currentPage.ToString();
            // 控制按钮状态
            btn_Up.Enabled = currentPage > 1;
            btn_Down.Enabled = currentPage < pageCount;
            // 空数据提示
            if (dgv_HistoryLog.Rows.Count == 0)
            {
                dgv_HistoryLog.DataSource = null;
            }
        }

        private async void btn_Up_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                await LoadPageData();
            }
        }

        private async void btn_Down_Click(object sender, EventArgs e)
        {
            if (currentPage < pageCount)
            {
                currentPage++;
                await LoadPageData();
            }
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            // 重置分页参数
            currentPage = 1;
            // 清空所有查询条件
            // 1. 时间选择器重置为当天
            dtp_StartTime.Value = DateTime.Today;
            dtp_EndTime.Value = DateTime.Today;
            // 2. 清空日志类型选择
            cbx_LogType.SelectedIndex = -1;
            // 3. 清空存储的查询条件
            currentStartTime = null;
            currentEndTime = null;
            currentLogType = "";
            // 4. 设置为普通查询模式
            isConditionSearch = false;
           // 5. 重置分页统计
            await InitializePagination();
            // 6. 加载数据
            await LoadPageData();
        }

        /// <summary>
        /// 最后一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_LastPage_Click(object sender, EventArgs e)
        {
            currentPage =Convert.ToInt32(this.lbl_CountPage.Text.Trim());
            await LoadPageData();
        }


        /// <summary>
        /// 跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Go_Click(object sender, EventArgs e)
        {
            string input = txt_Page.Text.Trim();
            if (string.IsNullOrEmpty(input))
            {
                MessageBox.Show("页码不能为空！");
                txt_Page.Focus();
                return;
            }
            if (!Regex.IsMatch(input, @"^\d+$"))
            {
                MessageBox.Show("请输入有效的数字！");
                txt_Page.Focus();
                return;
            }
            if (!int.TryParse(input, out int pageNumber))
            {
                MessageBox.Show("页码转换失败，请输入有效的数字！");
                txt_Page.Focus();
                return;
            }
            if (pageNumber < 1 || pageNumber > pageCount)
            {
                MessageBox.Show($"页码必须在 1 到 {pageCount} 之间！");
                txt_Page.Focus();
                return;
            }
            currentPage = pageNumber;
            await LoadPageData();
        }


        /// <summary>
        /// 限值输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Page_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许：数字、退格键(Backspace)、删除键(Delete)
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
            {
                e.Handled = true; // 阻止输入非数字字符
            }
        }


        /// <summary>
        /// 查询条件的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Find_Click(object sender, EventArgs e)
        {
            try
            {
                // 存储查询条件
                currentStartTime = dtp_StartTime.Value;
                currentEndTime = dtp_EndTime.Value;
                currentLogType = cbx_LogType.Text.Trim();
                isConditionSearch = true;

                // 重置到第一页
                currentPage = 1;

                // 获取总记录数
                var countResult = await SysLogService.GetSysLogTimeCount(
                    currentStartTime.Value,
                    currentEndTime.Value,
                    currentLogType
                );

                recordCount = countResult.Count;
                pageCount = (int)Math.Ceiling(recordCount / (double)pageSize);
                lbl_LogCount.Text = recordCount.ToString();
                lbl_CountPage.Text = pageCount.ToString();

                // 按时间升序排序
                typeLogs = countResult
                    .OrderBy(log => log.InsertTime)
                    .ToList();
                await LoadPageData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}");
            }
        }

        /// <summary>
        /// excel导出功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ExcelOutput_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前绑定的数据
                var data = dgv_HistoryLog.DataSource as List<SysLog>;
                if (data == null || data.Count == 0)
                {
                    MessageBox.Show("没有数据可导出！");
                    return;
                }

                // 创建保存文件对话框
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件|*.xlsx";
                saveDialog.Title = "导出日志";
                saveDialog.FileName = $"SystemLogs_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                if (saveDialog.ShowDialog() != DialogResult.OK)
                    return;

                // 使用ClosedXML创建Excel
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add("日志记录");

                    // 添加标题行
                    int col = 1;
                    foreach (DataGridViewColumn column in dgv_HistoryLog.Columns)
                    {
                        if (column.Visible)
                        {
                            worksheet.Cell(1, col).Value = column.HeaderText;
                            col++;
                        }
                    }

                    // 填充数据
                    int row = 2;
                    foreach (var log in data)
                    {
                        col = 1;
                        foreach (DataGridViewColumn column in dgv_HistoryLog.Columns)
                        {
                            if (column.Visible)
                            {
                                var value = log.GetType().GetProperty(column.DataPropertyName)?.GetValue(log);
                                worksheet.Cell(row, col).Value = value?.ToString();
                                col++;
                            }
                        }
                        row++;
                    }

                    // 自动调整列宽
                    worksheet.Columns().AdjustToContents();

                    // 保存文件
                    workbook.SaveAs(saveDialog.FileName);
                    MessageBox.Show("导出成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 导出所有数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ExcelAll_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                List<SysLog> exportData;

                if (isConditionSearch)
                {
                    if (typeLogs.Count == 0)
                    {
                        MessageBox.Show("没有符合条件的可导出数据！");
                        return;
                    }
                    exportData = typeLogs; // 使用条件查询的缓存数据
                }
                else
                {
                    if (noTypeLogs.Count == 0)
                    {
                        // 如果尚未初始化，则重新加载（容错处理）
                        await LoadAllNoConditionData();
                        if (noTypeLogs.Count == 0)
                        {
                            MessageBox.Show("没有可导出的数据！");
                            return;
                        }
                    }
                    exportData = noTypeLogs; // 使用初始化加载的缓存数据
                }

                // 创建保存文件对话框
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件|*.xlsx";
                saveDialog.Title = "导出所有日志";
                saveDialog.FileName = $"AllLogs_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    GenerateExcel(exportData, saveDialog.FileName);
                    MessageBox.Show("导出成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}");
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }



        // 保持原有的Excel生成方法不变
        private void GenerateExcel(List<SysLog> data, string filePath)
        {
            using (var workbook = new XLWorkbook())
            {

                var worksheet = workbook.Worksheets.Add("日志记录");

                // 动态排除SN字段
                var exportProperties = typeof(SysLog).GetProperties()
                    .Where(p => p.Name != "SN")
                    .ToList();

                // 添加标题行
                for (int i = 0; i < exportProperties.Count; i++)
                {
                    worksheet.Cell(1, i + 1).Value = exportProperties[i].Name;
                }

                // 填充数据（保持排序后的顺序）
                for (int row = 0; row < data.Count; row++)
                {
                    for (int col = 0; col < exportProperties.Count; col++)
                    {
                        var value = exportProperties[col].GetValue(data[row])?.ToString();
                        worksheet.Cell(row + 2, col + 1).Value = value;
                    }
                }

                worksheet.Columns().AdjustToContents();
                workbook.SaveAs(filePath);
            }
        }
    }
}
